package findElement;

import org.junit.Test;

public class BinarySearch {
	/**
	 * 二分查找，即折半查找。此算法必须先排序
	 */
	@Test
	public void fun() {
		int[] list = {1, 3, 4, 0};
		System.out.println(binarySearch(list, 3));
	}
	public int binarySearch(int[] list, int ele) {
		int low = 0, high = list.length - 1, mid;
		while(low < high) {
			mid = (low + high) / 2;
			if(ele == list[mid]) return mid;
			if(ele > list[mid])  low = mid;
			if(ele < list[mid])	 high = mid;
		}
		return -1;
	}
}	
